<template>
  <el-dialog v-model="visible" :title="$t('competition.modules.titleModule.selectImage')" width="800px" align-center
    :destroy-on-close="true" :close-on-click-modal="false">
    <div class="image-selector-content">
      <!-- 预设图片网格 -->
      <div class="grid grid-cols-2 gap-4 mb-6">
        <div v-for="(image, index) in presetImages" :key="index" class="relative cursor-pointer group"
          @click="selectImage(image.path)">
          <div :class="[
            'w-full h-[82px] border-2 rounded-lg overflow-hidden transition-all duration-200',
            selectedImage === image.url
              ? 'border-blue-500 ring-2 ring-blue-200'
              : 'border-gray-200 hover:border-gray-300'
          ]">
            <img :src="image.url" :alt="image.name" class="w-full h-full object-cover" @load="handleImageLoad"
              @error="handleImageError" />
          </div>
          <!-- 选中状态指示器 -->
          <div v-if="selectedImage === image.url"
            class="absolute top-2 right-2 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
            <el-icon class="text-white text-sm">
              <Check />
            </el-icon>
          </div>
        </div>

        <!-- 上传自定义图片选项 -->
        <div class="relative cursor-pointer group" @click="triggerUpload">
          <div
            class="w-full h-[120px] border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center hover:border-blue-500 transition-colors duration-200">
            <el-icon class="text-3xl text-gray-400 mb-2">
              <Plus />
            </el-icon>
            <span class="text-sm text-gray-600">{{ $t('competition.modules.titleModule.uploadCustom') }}</span>
          </div>
          <div class="text-center text-sm text-gray-600 mt-2">自定义上传</div>
        </div>
      </div>

      <!-- 隐藏的文件上传输入 -->
      <input ref="fileInputRef" type="file" accept="image/png,image/jpeg,image/jpg" style="display: none"
        @change="handleFileSelect" />

      <!-- 
      <ImageListUpload
        :stemImages="imgList"
        actionImgStyle="width: 252px;height: 114px;" :imgNumber="3" :limit-size-img="5"
        @update:stemImages="(v) => { imgList[imgList.length - 1].path = v[imgList.length - 1]?.path || '' }" /> -->
    </div>

    <template #footer>
      <div class="flex justify-end space-x-3">
        <el-button @click="handleCancel">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="!selectedImage" :loading="uploading">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Check } from '@vben/icons'
import { $t } from '#/locales'
import { obsUpload } from '#/utils/obs'
import ImageListUpload from "#/components/common/image-list-upload.vue"

import { getImgUrl } from '#/utils/getImgUrl'
import { bufferToBase64 } from '#/utils/bufferToBase64'
// 预设图片数据
interface PresetImage {
  name: string
  url: string
  preview: string
  path: string
}
const imgList = ref([
  {
    id: 'preset-blue-bg',
    path: '系统租户_-1/competition/1750674911055_主KV 1_978e9a08-dd8e-45f4-a498-0a7e34e0f952.png',
  },
  {
    id: 'preset-green-bg',
    path: '系统租户_-1/competition/Snipaste_2025-08-18_14-26-02_7d2b072b-6149-41a7-a0c0-59834ed6ba35.png',
  },
  {
    id: 'user-upload',
    path: '',
  }
])

// 预设图片列表 - 这里使用一些示例图片，实际项目中应该配置真实的预设图片
const presetImages: PresetImage[] = [
  {
    name: '经典蓝色',
    url: 'preset-blue-bg',
    preview: '',
    path: '系统租户_-1/competition/1750674911055_主KV 1_978e9a08-dd8e-45f4-a498-0a7e34e0f952.png'
  },
  {
    name: '优雅紫色',
    url: 'preset-purple-bg',
    preview: '',
    path: '系统租户_-1/competition/Snipaste_2025-08-18_14-26-02_7d2b072b-6149-41a7-a0c0-59834ed6ba35.png',
  },
  // {
  //   name: '温暖橙色',
  //   url: 'preset-orange-bg',
  //   preview: ''
  // },
  // {
  //   name: '清新绿色',
  //   url: 'preset-green-bg',
  //   preview: ''
  // },
  // {
  //   name: '深邃灰色',
  //   url: 'preset-gray-bg',
  //   preview: ''
  // },
  // {
  //   name: '商务深蓝',
  //   url: 'preset-darkblue-bg',
  //   preview: ''
  // }
]

interface Props {
  visible: boolean
  currentImage?: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'confirm': [imageUrl: string]
}>()

// 响应式状态
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const selectedImage = ref<string>('')
const uploading = ref(false)
const fileInputRef = ref<HTMLInputElement>()

// 选择图片
const selectImage = (path: string) => {
  selectedImage.value = path
}

// 触发文件上传
const triggerUpload = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  // 验证文件类型
  const allowedTypes = ['image/bmp', 'image/png', 'image/jpeg', 'image/jpg']
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error($t('common.imageFormatTxt'))
    return
  }

  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error($t('common.imageSizeLimitTxt', ['5']))
    return
  }

  try {
    uploading.value = true
    const obsKey = await obsUpload(file.name, file)
    selectedImage.value = obsKey
    ElMessage.success($t('common.uploadSuccessTxt'))
  } catch (error) {
    ElMessage.error($t('common.uploadFailTxt'))
  } finally {
    uploading.value = false
    // 清空文件输入
    if (target) target.value = ''
  }
}

// 处理图片加载
const handleImageLoad = () => {
  // 图片加载成功
}

// 处理图片加载错误
const handleImageError = () => {
  // 图片加载失败
}

// 处理取消
const handleCancel = () => {
  selectedImage.value = ''
  visible.value = false
}

// 处理确认
const handleConfirm = () => {
  if (selectedImage.value) {
    emit('confirm', selectedImage.value)
    visible.value = false
  }
}

// 图片加载处理
const loadImage = async (image: PresetImage) => {
  if (!image.path) {
    image.url = ''
    // image.loading = false
    return
  }

  try {
    // imageLoading.value = true
    const src = await getImgUrl(image.path) as any
    const base64Content = bufferToBase64(src)
    image.url = base64Content
    // imageLoaded.value = true
  } catch (error) {
    // console.error($t('competition.validation.imageLoadFailed'), error)
    image.url = ''
    // imageLoaded.value = false
  } finally {
    // imageLoading.value = false
  }
}

// 监听弹窗打开，初始化选中状态
watch(() => props.visible, (isVisible) => {
  if (isVisible && props.currentImage) {
    selectedImage.value = props.currentImage
  } else if (isVisible) {
    selectedImage.value = ''
    presetImages.forEach((image) => {
      loadImage(image)
    })
  }
})
</script>

<style scoped>
.image-selector-content {
  max-height: 400px;
  overflow-y: auto;
}

/* 自定义滚动条样式 */
.image-selector-content::-webkit-scrollbar {
  width: 6px;
}

.image-selector-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.image-selector-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.image-selector-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
